﻿using DoNetDrive.Core.Command;
using DoNetDrive.Core.Connector;
using DotNetty.Buffers;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.Command
{
    public class WebSocketIOObserverHandler : INRequestHandle
    {
        public delegate void DisposeEventHandler(INConnector connector, string message, IByteBuffer filebuf);
        public delegate void OnLogEventHandler(INConnector connector, string message, int fileSize);
        Encoding UTF8 = Encoding.UTF8;
        //   public event DisposeEventHandler DisposeResponseEvent;
        public event DisposeEventHandler OnMessageEvent;
        public event OnLogEventHandler OnReceiveEvent;

        public event OnLogEventHandler OnSendEvent;
        public void Dispose()
        {

        }

        public void DisposeRequest(INConnector connector, IByteBuffer msg)
        {
            try
            {
                var iLen = msg.ReadInt();
                var sJson = msg.ReadString(iLen, UTF8);
                try
                {
                    OnReceiveEvent?.Invoke(connector, sJson, msg.ReadableBytes);//通讯日志
                }
                finally
                {

                    
                }
                var IsMessage = sJson.Contains("\"msgtype\":",StringComparison.CurrentCultureIgnoreCase);
                if (IsMessage )
                {
                    OnMessageEvent?.Invoke(connector, sJson, msg);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("TCPIOObserverHandler：DisposeRequest 解析数据失败:" + ex.Message);
            }
        }

        public void DisposeResponse(INConnector connector, IByteBuffer msg)
        {
            try
            {
                var iLen = msg.ReadInt();
                var sJson = msg.ReadString(iLen, UTF8);
                OnSendEvent?.Invoke(connector, sJson, msg.ReadableBytes);
            }
            catch (Exception ex)
            {
                Console.WriteLine("TCPIOObserverHandler：DisposeResponse 解析数据失败:" + ex.Message);
            }
        }
    }
}
